package com.example.administrator.testproject.download.util;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.example.administrator.testproject.download.RxRetrofitApp;
import com.example.administrator.testproject.download.bean.LiteOrmDownInfo;
import com.litesuits.orm.LiteOrm;
import com.litesuits.orm.db.assit.QueryBuilder;

import java.util.ArrayList;
import java.util.List;


/**
 * 断点续传
 * 数据库工具类-geendao运用
 * Created by WZG on 2016/10/25.
 */

public class LiteDbDownUtil extends BaseUtils{
    private static LiteDbDownUtil db;
    private final static String dbName = "edu_db";
    private Context context;
    private LiteOrm liteOrm;

    public LiteDbDownUtil() {
        context= RxRetrofitApp.getApplication();
        liteOrm = LiteOrm.newCascadeInstance(context, dbName);
    }

    /**
     * 获取单例
     * @return
     */
    public static LiteDbDownUtil getInstance() {
        if (db == null) {
            synchronized (LiteDbDownUtil.class) {
                if (db == null) {
                    db = new LiteDbDownUtil();
                }
            }
        }
        return db;
    }

    /**
     * 获取可读数据库
     */
    private SQLiteDatabase getReadableDatabase() {
        SQLiteDatabase db = liteOrm.getReadableDatabase();
        return db;
    }

    /**
     * 获取可写数据库
     */
    private SQLiteDatabase getWritableDatabase() {
        SQLiteDatabase db = liteOrm.getWritableDatabase();
        return db;
    }

    public  List<LiteOrmDownInfo> queryDownAll() {
        List<LiteOrmDownInfo> qb = liteOrm.query(LiteOrmDownInfo.class);
        return qb;
    }

    public void save(LiteOrmDownInfo info){
        liteOrm.insert(info);
    }

    public void update(LiteOrmDownInfo info){
        liteOrm.update(info);
    }

    public void deleteDowninfo(LiteOrmDownInfo info){
        liteOrm.delete(info);
    }


    public LiteOrmDownInfo queryDownBy(long Id) {
        //模糊查询
        QueryBuilder<LiteOrmDownInfo> qb =
                new QueryBuilder<LiteOrmDownInfo>(LiteOrmDownInfo.class)
                        .whereEquals("id", Id);

        ArrayList<LiteOrmDownInfo> query = liteOrm.query(qb);
        if(query.isEmpty()){
            return null;
        }else{
            return query.get(0);
        }
    }


}
